package core

import (
	"errors"
	"fmt"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/goRpc"
	"go.uber.org/zap"
	"net"
	"net/rpc"
	"reflect"
)

// RpcRegistry 用于追踪已注册的RPC服务
type RpcRegistry struct {
	services map[string]reflect.Type
}

// RegisterService 注册服务
func (r *RpcRegistry) RegisterService(name string, rcvr interface{}) error {
	rpc.RegisterName(name, rcvr)

	if r.services == nil {
		r.services = make(map[string]reflect.Type)
	}

	if _, ok := r.services[name]; ok {
		return errors.New("service already registered: " + name)
	}

	r.services[name] = reflect.TypeOf(rcvr)
	return nil
}

// Services 返回所有已注册的服务
func (r *RpcRegistry) Services() map[string]reflect.Type {
	return r.services
}

func GoRpc() {
	registry := &RpcRegistry{}
	err := registry.RegisterService("Classified", new(goRpc.ClassifiedRpc))
	if err != nil {
		global.GVA_LOG.Error("注册服务失败:", zap.Error(err))
	}

	// 查看已注册的服务
	services := registry.Services()
	for serviceName, serviceType := range services {
		global.GVA_LOG.Info(fmt.Sprintf("已注册的服务: %s, 类型: %v\n", serviceName, serviceType))
	}

	// 启动RPC服务器
	listener, err := net.Listen("tcp", "localhost:1234")
	if err != nil {
		global.GVA_LOG.Error("监听失败:", zap.Error(err))
	}
	defer listener.Close()

	for {
		conn, err := listener.Accept()
		if err != nil {
			global.GVA_LOG.Error("接受连接失败:", zap.Error(err))
		}
		go rpc.ServeConn(conn)
	}
}

// Arithmetic 定义了一个简单的算术服务
type Arithmetic struct{}

// Add 实现加法操作
func (a *Arithmetic) Add(args *AddArgs, reply *int) error {
	*reply = args.A + args.B
	return nil
}

// AddArgs 定义了Add方法的参数
type AddArgs struct {
	A, B int
}
